package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Menu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Service
@Slf4j
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Menu> page = menuDao.findByCondition(queryPageBean.getQueryString());
        log.debug("MenuService__findByCondition:{" + page + "}");
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public void add(Menu menu) {
        Menu menuDB = menuDao.findByName(menu.getName());
        if (menuDB != null) {
            log.debug("菜单已存在,请重新添加!!");
            throw new BusinessRuntimeException("菜单已存在,请重新添加!!");
        }
        menuDao.add(menu);
    }

    @Override
    public void deleteById(Integer id) {
        //校验数据
        Integer count = menuDao.findCountByMenuId(id);
        if (count > 0) {
            log.debug("菜单与角色有数据关联,无法删除!!!");
            throw new BusinessRuntimeException("菜单与角色有数据关联,无法删除!!!");
        }
        menuDao.deleteById(id);
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public void update(Menu menu) {
        menuDao.update(menu);
    }
}
